<template>
  <div class="container">
    <a-card class="general-card">
      <ProTable
        :header-title="false"
        :columns="columns"
        :defaultFormData="{type:'',name:''}"
        :request="(params) => getServiceList({ ...params, condition: { type: params.type,name: params.name } })"
        :action-ref="setActionRef"
        row-key="id"
        style="margin-top: 20px"
        :lightSearchConfig = "{
          rowNumber: 4
        }"
      >
        <template #isOnline="{ record }">
          <span>{{ record.status === 0 ? "启用" : "禁用" }}</span>
        </template>
        <template #image="{ record }">
          <a-image :src="record.image" width="50" height="50" />
        </template>
        <template #operation="{ record }">
          <a-button v-auth="'serviceEidtBtn'" type="text" @click="editService(record)">编辑</a-button>
          <a-popconfirm  content="确认删除么"  @ok="deleteService(record.id)">
          <a-button v-auth="'serviceDelBtn'" type="text" status="danger"
            >删除</a-button
          >
        </a-popconfirm>
        </template>
        <template #option-render="{ dom }">
          <component :is="dom[1]" />
          <component :is="dom[0]" />
          <a-button v-auth="'refundRuleBtn'" type="primary" @click="ruleHandle">退改规则</a-button>
          <a-button v-auth="'addServiceBtn'" type="primary" html-type="submit" @click="openAddModal"
            >添加服务</a-button
          >
      
        </template>
      </ProTable>

      <!-- 编辑/添加 Modal -->
      <a-drawer
        v-model:visible="modalVisible"
        title="服务信息"
        :width="1300"
        @ok="handleOk"
      >
        <a-form
          :model="currentService"
          :rules="rules"
          layout="vertical"
          ref="formRef"
        >
          <a-form-item label="服务类型" field="type">
            <a-select  placeholder="请选择服务类型" v-model="currentService.type">
              <a-option :value="1">保洁</a-option>
              <a-option :value="2">搬家</a-option>
              <a-option :value="3">保养</a-option>
              <a-option :value="4">维修</a-option>
            </a-select>
          </a-form-item>
          <!-- <a-form-item label="产品代码" field="productCode">
            <a-input v-model="currentService.productCode" placeholder="请输入产品代码" />
          </a-form-item>
          <a-form-item label="产品编号" field="productNo">
            <a-input v-model="currentService.productNo"  placeholder="请输入产品编号" />
          </a-form-item> -->
          <a-form-item label="服务名称" field="name">
            <a-input v-model="currentService.name" placeholder="请输入服务名称" />
          </a-form-item>
          <a-form-item label="封面图片" field="image">
            <div v-if="currentService.image">
              <a-image :src="currentService.image" width="100" height="100" />
              <a-button type="text" @click="currentService.image = ''">删除图片</a-button>
            </div>
            <div v-else>
              <a-upload
                action="https://fuwu-test.habitat.cn/service/system/upload"
                :show-file-list="false"
                :data="{ type: 1 }"
                @success="handleUploadSuccess"
              >
                <a-button type="primary">上传图片</a-button>
              </a-upload>
            </div>
          </a-form-item>
          <!-- <a-form-item label="服务详情" field="content" hidden>
            <TEditor  v-model="currentService.content">
              
            </TEditor>
   
            
          </a-form-item> -->

          <a-form-item label="服务内容" field="serviceContent">
            <a-textarea  v-model="currentService.serviceContent" placeholder="请输入服务内容" />
          </a-form-item>
          <a-form-item label="注意事项" field="carefulRemark">
            <a-textarea  v-model="currentService.carefulRemark" placeholder="请输入注意事项" />
          </a-form-item>

          <a-form-item label="优惠备注" field="discountRemark">
            <a-input v-model="currentService.discountRemark" placeholder="请输入优惠备注" />
          </a-form-item>
          <a-form-item label="状态" field="status">
            <a-switch
              v-model="currentService.status"
              :checked-value="0"
              :unchecked-value="1"
            />
          </a-form-item>

          <!-- 嵌套表格 -->
          <a-form  :model="specForm"  direction="vertical">
            <a-form-item v-for="(post, index) of specForm.posts" :field="`posts[${index}].value`" :label="`${post.name}`" :key="index">
              <a-space wrap  >
                <a-tag
                checkable size="large"
                  v-for="(tag, tagIndex) of post.value"
                  :key="tag"
                  :closable="tagIndex !== 0"
                  @close="handleRemoveTag(post, tag)"
                >
                  {{ tag }}
                </a-tag>

                <a-input
                  v-if="showInput && activePost === post"
                  ref="inputRef"
                  :style="{ width: '90px'}"
                  size="mini"
                  v-model.trim="inputVal"
                  @keyup.enter="handleAddTag(post)"
                  @blur="handleAddTag(post)"
                />
                <a-tag
                size="large"
                  v-else
                  :style="{
                    width: '90px',
                    backgroundColor: 'var(--color-fill-2)',
                    border: '1px dashed var(--color-fill-3)',
                    cursor: 'pointer',
                  }"
                  @click="handleEditTag(post)"
                >
                  <template #icon>
                    <icon-plus />
                  </template>
                  添加规格
                </a-tag>
              </a-space>
              <a-button @click="handleDelete(index)" :style="{ marginLeft: '10px' }">Delete</a-button>
            </a-form-item>
          </a-form>

        
            <pro-table
              :header-title="false"
              :columns="subColumns"
              :data="currentService.specList"
              row-key="specSkuId"
              :pagination="false"
              style="margin-bottom: 10px;width: auto;"
            >
              <template #operation="{ record }">
                <a-button
                  type="text"
                  status="danger"
                  @click="deleteSpec(record.specSkuId)"
                  >删除</a-button
                >
              </template>
              <template #option-render>
                <a-button type="primary" html-type="submit" @click="openAddSpecModal">添加规格</a-button
                >
              </template>

              
              <template #name="{ record, rowIndex }">
                <a-input v-model="record.name" />
              </template>
              <template #officialPrice="{ record, rowIndex }">
                <a-input-number v-model="record.officialPrice" />
              </template>
              <template #discountPrice="{ record, rowIndex }">
                <a-input-number v-model="record.discountPrice" />
              </template>
              <template #staffPrice="{ record, rowIndex }">
                <a-input-number v-model="record.staffPrice" />
              </template>

              <template #minOrderNum="{ record, rowIndex }">
                <a-input-number v-model="record.minOrderNum" />
              </template>
              <template #defaultDuration="{ record, rowIndex }">
                <a-input-number v-model="record.defaultDuration" />
              </template>
              <template #defaultPeopleNum="{ record, rowIndex }">
                <a-input-number v-model="record.defaultPeopleNum" />
              </template>
              <template #addAreaNum="{ record, rowIndex }">
                <a-input-number v-model="record.addAreaNum" />
              </template>
              <template #addTimeNum="{ record, rowIndex }">
                <a-input-number v-model="record.addTimeNum" />
              </template>


            </pro-table>
    
        </a-form>
      </a-drawer>

      <!-- 添加规格 Modal -->
      <a-modal
        :width="800"
        v-model:visible="addSpecModalVisible"
        title="添加规格"
        @ok="handleAddSpec"
        @cancel="addSpecModalVisible = false"
      >
        <a-form  ref="specForms" :model="newSpec" :rules="specRules" label-col="{ span: 12 }" wrapper-col="{ span: 12 }" layout="vertical">
          <a-form-item label="规格名称" field="name">
            <a-input v-model="newSpec.name" />
          </a-form-item>
          <a-form-item label="官方价格" field="officialPrice">
            <a-input-number v-model="newSpec.officialPrice" />
          </a-form-item>
          <a-form-item label="优惠价格" field="discountPrice">
            <a-input-number v-model="newSpec.discountPrice" />
          </a-form-item>
          <a-form-item label="员工价格" field="staffPrice">
            <a-input-number v-model="newSpec.staffPrice" />
          </a-form-item>
          <a-form-item label="最小起订量" field="minOrderNum">
            <a-input-number v-model="newSpec.minOrderNum" />
          </a-form-item>
          <a-form-item label="默认时常" field="defaultDuration">
            <a-input-number v-model="newSpec.defaultDuration" />
          </a-form-item>
          <a-form-item label="默认人数" field="defaultPeopleNum">
            <a-input-number v-model="newSpec.defaultPeopleNum" />
          </a-form-item>
          <a-form-item label="每增加多少平米增加1小时" field="addAreaNum">
            <a-input-number v-model="newSpec.addAreaNum" />
          </a-form-item>
          <a-form-item label="每超过多少小时增加1人" field="addTimeNum">
            <a-input-number v-model="newSpec.addTimeNum" />
          </a-form-item>
          <a-form-item label="选择父级规格" field="parentSpecSkuId">
            <a-tree-select
              v-model="newSpec.parentSpecSkuId"
              :data="specTreeData"
              placeholder="请选择父级规格"
              :allow-clear="true"
            />
          </a-form-item>
        </a-form>
      </a-modal>

      <a-modal v-model:visible="ruleModalVisible" title="退改规则" @ok="saveRefHandle">
        <a-form layout="vertical" :model="ruleForm">
          <a-form-item label="保洁" field="content1">
            <a-textarea v-model="ruleForm.content1" placeholder="请输入保洁退改规则" />
          </a-form-item>
          <a-form-item label="搬家" field="content2">
            <a-textarea v-model="ruleForm.content2" placeholder="请输入搬家退改规则" />
          </a-form-item>
          <a-form-item label="保养" field="content3">
            <a-textarea v-model="ruleForm.content3" placeholder="请输入保养退改规则" />
          </a-form-item>
          <a-form-item label="维修" field="content4">
            <a-textarea v-model="ruleForm.content4" placeholder="请输入维修退改规则" />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>
<script>
import { reactive, ref, onMounted, nextTick,computed } from "vue";
import TEditor from "@/components/TEditor/index.vue";
import { Message } from "@arco-design/web-vue";
import {
  getServiceList,
  saveServiceProduct,
  deleteServiceProduct,
  getServiceDetail,
  saveSpec,
  getRefundSpecDetail,
  saveRefundSpec
} from "@/api/service";
import Editor from '@tinymce/tinymce-vue'

export default {
  components: {
    Editor,
    TEditor
  },
  setup() {
    const specForms = ref(null);
    const serviceList = ref([]);
    const modalVisible = ref(false);
    const addSpecModalVisible = ref(false);
    const isEdit = ref(false);
    const formRef = ref(null);
    const actionRef = ref();
    const setActionRef = (ref) => {
    actionRef.value = ref;
  };
    const ruleModalVisible = ref(false);
    const currentService = reactive({
      id: null,
      type: 1,
      productCode: "",
      productNo: "",
      name: "",
      image: "",
      content: "",
      discountRemark: "",
      status: 1,
      specList: [],
      specRelList: [],
      carefulRemark: "",
      serviceContent: ""
    });
    const ruleForm = ref({
      content1: "",
      content2: "",
      content3: "",
      content4: "",
    });
    const specForm = reactive({
      name: "",
      specValueName: "",
      posts: []
    });
    const handleAddItem = (form) => {
      console.log(form,'-form')
      specForm.posts.push({
        value: [],
        name: form.name
      });
    };
    const handleDelete = (index) => {
      specForm.posts.splice(index, 1);
    }
    const handleUploadSuccess = (file, fileList) => {
    // 假设返回的数据在file.response中
    const response = file.response;
    if (response && response.success && response.data) {
      // 将返回的URL设置到表单的image字段
      console.log(response, currentService)
      currentService.image = response.data.url;
    }
  };
    const newSpec = reactive({
      specName: "",
      officialPrice: 0,
      discountPrice: 0,
      staffPrice: 0,
      minOrderNum: 0,
      defaultDuration: 0,
      defaultPeopleNum: 0,
      addAreaNum:0,
      addTimeNum:0,
      parentSpecSkuId: null, // 新增父级规格ID
    });

    // 子服务表格列配置
    const subColumns = [
      { title: "规格名称", dataIndex: "name", hideInSearch: true,slotName:'name' ,ellipsis:true},
      { title: "官方价格", dataIndex: "officialPrice", hideInSearch: true,slotName:'officialPrice' ,ellipsis:true},
      { title: "优惠价格", dataIndex: "discountPrice", hideInSearch: true,slotName:'discountPrice',ellipsis:true },
      { title: "员工价格", dataIndex: "staffPrice", hideInSearch: true,slotName:'staffPrice' ,ellipsis:true},
      { title: "最小起订量", dataIndex: "minOrderNum", hideInSearch: true,slotName:'minOrderNum',ellipsis:true },
      { title: "默认时常", dataIndex: "defaultDuration", hideInSearch: true,slotName:'defaultDuration' ,ellipsis:true},
      { title: "默认人数", dataIndex: "defaultPeopleNum", hideInSearch: true,slotName:'defaultPeopleNum' ,ellipsis:true},
      { title: "每增加多少平米增加1小时", dataIndex: "addAreaNum", hideInSearch: true,slotName:'addAreaNum',ellipsis:true },
      { title: "每超过多少小时增加1人", dataIndex: "addTimeNum", hideInSearch: true,slotName:'addTimeNum', ellipsis:true},
      {
        title: "操作",
        dataIndex: "operation",
        slotName: "operation",
        hideInSearch: true,
      },
    ];

    // 表格列配置
    const columns = [
      { title: "服务编号", dataIndex: "id",hideInSearch:true },
      { title: "服务类型", dataIndex: "type" ,     valueEnum: {
          1: { text: '保洁' },
          2: { text: '搬家' },
          3: { text: '保养' },
          4: { text: '维修' },

        }},
      // { title: "产品代码", dataIndex: "productCode",hideInSearch:true  },
      // { title: "产品编号", dataIndex: "productNo",hideInSearch:true  },
      { title: "服务名称", dataIndex: "name" },
      { title: "封面图片", dataIndex: "image" ,hideInSearch:true ,slotName:'image'},
      { title: "优惠备注", dataIndex: "discountRemark",hideInSearch:true  },
      {
        title: "状态",
        dataIndex: "status",
        slotName: "isOnline",
        hideInSearch:true 
      },
      { title: "创建时间", dataIndex: "createTime", hideInSearch: true  },
      {
        title: "操作",
        dataIndex: "operation",
        slotName: "operation",
        hideInSearch:true 
      },
    ];

    // 表单验证规则
    const rules = {
      type: [{ required: true, message: "请输入服务类型" }],
      productCode: [{ required: true, message: "请输入产品代码" }],
      productNo: [{ required: true, message: "请输入产品编号" }],
      name: [{ required: true, message: "请输入服务名称" }],
    };

    // 规格表单验证规则
    const specRules = {
      specName: [{ required: true, message: "请输入规格名称" }],
      officialPrice: [{ required: true, message: "请输入官方价格" }],
      discountPrice: [{ required: true, message: "请输入优惠价格" }],
      staffPrice: [{ required: true, message: "请输入员工价格" }],
    };

    // 添加规格
    const addSpecGroup = async () => {
      // await saveSpec( specForm);
      handleAddItem(specForm);
      Message.success("规格组添加成功");
    }

    // 动态添加规格
    const addSpec = () => {
      currentService.specList.push({
        specSkuId: `S${Date.now()}`, // 动态生成规格ID
        officialPrice: 0,
        discountPrice: 0,
        staffPrice: 0,
        minOrderNum: 0,
        defaultDuration: 0,
        defaultPeopleNum: 0,
        addAreaNum:0,
        addTimeNum:0,

      });
    };

    // 删除规格
    const deleteSpec = (specSkuId) => {
  const removeSpec = (specList, specSkuId) => {
    for (let i = 0; i < specList.length; i++) {
      if (specList[i].specSkuId === specSkuId) {
        specList.splice(i, 1);
        return true;
      }
      if (specList[i].children) {
        if (removeSpec(specList[i].children, specSkuId)) {
          return true;
        }
      }
    }
    return false;
  };

  if (removeSpec(currentService.specList, specSkuId)) {
    Message.success("规格删除成功");
  } else {
    Message.error("规格删除失败");
  }
};

    // 模拟接口: 添加/编辑服务
    const saveService = async () => {
  // 构建请求数据
  console.log(currentService,'---')
  const requestData = {
    id: currentService.id,
    type: currentService.type,
    productCode: currentService.productCode,
    productNo: currentService.productNo,
    name: currentService.name,
    image: currentService.image,
    content: currentService.content,
    discountRemark: currentService.discountRemark,
    status: currentService.status,
    specList:  currentService.specList,
    carefulRemark: currentService.carefulRemark,
    serviceContent:currentService.serviceContent

  };

  try {
    const response = await saveServiceProduct(requestData);
    if (response.success) {
      Message.success(isEdit.value ? "服务修改成功" : "服务添加成功");
      modalVisible.value = false; // 只有在保存成功后才关闭抽屉
      actionRef.value.reload()
    } else {
      return
      // throw new Error(response.message);
    }
  } catch (error) {
    Message.error(error.message || "保存失败，请重试");
  }
};

  

// 打开添加服务的模态框
    const openAddModal = () => {
      isEdit.value = false;
      Object.keys(currentService).forEach(
        (key) => (currentService[key] = key === "specList" || key === "specRelList" ? [] : "")
      );
      modalVisible.value = true;
    };

    // 编辑服务
    const editService = async (record) => {
      isEdit.value = true;
      const response = await getServiceDetail(record.id);
      if (response) {
     
        Object.keys(currentService).forEach((key) => {
          currentService[key] = response.data[key];
        });
        // specTreeData.value = generateSpecTreeData(currentService.specList); // 更新规格树数据
        modalVisible.value = true;
      } else {
        Message.error(response.message);
      }
    };

    // 删除服务
    const deleteService = async (id) => {

      const response = await deleteServiceProduct(id);
      if (response) {
        Message.success("服务删除成功");
        actionRef.value.reload()
      } else {
        Message.error(response.message);
      }
    };

    // 确认保存
    const handleOk = async () => {
  try {
   const rule =  await formRef.value.validate();
   if(!rule){
    await saveService();
      // 验证通过，执行保存操作
      modalVisible.value = false; // 只有在保存成功后才关闭抽屉
      formRef.value.resetFields();
      actionRef.value.reload()
   }
  
  } catch (errors) {
    console.error('表单验证失败：', errors);
    // 可以在这里添加一些错误提示
    Message.error('请填写所有必填字段');
  }
};

    // 打开添加规格的模态框
    const openAddSpecModal = () => {
      
      specForms.value.resetFields();
      addSpecModalVisible.value = true;
    };
    
    const findParentSpec = (specList, parentSpecSkuId) => {
      for (const spec of specList) {
        if (spec.specSkuId === parentSpecSkuId) {
          return spec;
        }
        if (spec.children) {
          const found = findParentSpec(spec.children, parentSpecSkuId);
          if (found) {
            return found;
          }
        }
      }
      return null;
    };

    // 确认添加规格
    const handleAddSpec = () => {
      const parentSpec = findParentSpec(currentService.specList, newSpec.parentSpecSkuId);
      if (parentSpec) {
        if (!parentSpec.children) {
          parentSpec.children = [];
        }
        parentSpec.children.push({
          specSkuId: `S${Date.now()}`, // 动态生成规格ID
          ...newSpec,
        });
      } else {
        currentService.specList.push({
          specSkuId: `S${Date.now()}`, // 动态生成规格ID
          ...newSpec,
        });
      }
      addSpecModalVisible.value = false;
      Message.success("规格添加成功");
      // specTreeData.value = generateSpecTreeData(currentService.specList); // 更新规格树数据
      newSpec.specName = "";
      newSpec.officialPrice = 0;
      newSpec.discountPrice = 0;
      newSpec.staffPrice = 0;

      newSpec.minOrderNum = 0;
      newSpec.defaultDuration = 0;
      newSpec.defaultPeopleNum = 0;
      newSpec.addAreaNum = 0;
      newSpec.addTimeNum = 0;

      newSpec.parentSpecSkuId = null;
      console.log(newSpec)
    };

    const tags = ref(['Tag 1', 'Tag 2', 'Tag 3']);
    const inputRef = ref(null);
    const showInput = ref(false);
    const inputVal = ref('');
    const activePost = ref(null);

    const handleEditTag = (post) => {
      showInput.value = true;
      activePost.value = post;

      nextTick(() => {
        if (inputRef.value) {
          inputRef.value.focus();
        }
      });
    };

    const handleAddTag = (post) => {
      if (inputVal.value) {
        post.value.push(inputVal.value);
        inputVal.value = '';
      }
      showInput.value = false;
      activePost.value = null;
    };

    const handleRemoveTag = (post, tag) => {
      post.value = post.value.filter((t) => t !== tag);
    };

    // 生成规格树数据
    const generateSpecTreeData = (specList) => {
      const treeData = specList.map(spec => ({
        key: spec.specSkuId,
        title: spec.name,
        children: spec.children ? generateSpecTreeData(spec.children) : [],
      }));
      return treeData;
    };

    const specTreeData = computed(() => {
      return generateSpecTreeData(currentService.specList);
    })  


    const  ruleHandle = async()=>{
      const res = await getRefundSpecDetail();
      ruleForm.value = res.data;
      ruleModalVisible.value = true
    }

    const saveRefHandle = async()=>{
      const res = await saveRefundSpec(ruleForm.value);
      Message.success('保存成功');
    }

    return {
      formRef,
      serviceList,
      columns,
      modalVisible,
      addSpecModalVisible,
      currentService,
      newSpec,
      subColumns,
      rules,
      specRules,
      specForm,
      openAddModal,
      editService,
      deleteService,
      addSpec,
      deleteSpec,
      handleOk,
      openAddSpecModal,
      handleAddSpec,
      getServiceList,
      addSpecGroup,
      handleAddItem,
      handleDelete,
      handleAddTag,
      handleRemoveTag,
      handleEditTag,
      inputRef,
      showInput,
      inputVal,
      activePost,
      specTreeData,
      handleUploadSuccess,
      setActionRef,
      specForms,
      ruleModalVisible,
      ruleForm,
      saveRefHandle,
      ruleHandle
    };
  },
};
</script>

<style scoped lang="less">
.container {
  padding: 20px 20px 20px 20px;
}
:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}
.action-icon {
  margin-left: 12px;
  cursor: pointer;
}
.active {
  color: #0960bd;
  background-color: #e3f4fc;
}
.setting {
  display: flex;
  align-items: center;
  width: 200px;
  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}
</style>